package com.google.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class ProcessorHandler implements Runnable {
    Socket socket;
    Object service;

    public ProcessorHandler(Object service,Socket socket) {
        this.socket = socket;
        this.service=service;
    }

    @Override
    public void run() {
        System.out.println("begin ProcesserorHandler");
        ObjectInputStream inputStream=null;
        try{
            inputStream=new ObjectInputStream(socket.getInputStream());
            RPCRequest request=(RPCRequest)inputStream.readObject();
            Object result=invoke(request);
            ObjectOutputStream outputStream=new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(result);
            outputStream.flush();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Object invoke(RPCRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object[]args=   request.getParams();//得到请求的参数
        Class<?>[]types=new Class[args.length];
        for(int i=0;i<args.length;i++){
             types[i]=args[i].getClass();
        }
        //现在要调用哪个类
        //request.getClassName();
        Method method=service.getClass().getMethod(request.getMethodName(),types);
        return method.invoke(service,args);
    }
}
